<template>
    <el-scrollbar height="560">
        <el-tree
            ref="treeRef"
            :data="treeData"
            :show-checkbox="multiple"
            :current-node-key="currentNodeKey"
            node-key="id"
            empty-text="暂无数据"
            default-expand-all
            highlight-current
            :props="defaultProps"
            @node-click="nodeClickHandle" />
    </el-scrollbar>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import type { PropType } from 'vue';
import { ElTree, ElScrollbar } from 'element-plus';
import { TypeTree, TypeOptions, TypeFetchApi } from '../type';
import { type } from '../../../utils/index';

const treeRef = ref<InstanceType<typeof ElTree>>();
const treeData = ref<Array<TypeTree>>();

const currentNodeKey = computed({
    set(val: string | number) {
        emits('update:modelValue', val);
    },
    get() {
        return props.modelValue;
    }
});

interface PropsType {
    modelValue: number | string; //  选中的分组 默认为默认分组
    multiple: boolean; // 是否多选，true 为多选  false 为单选  默认为单选
    defaultProps: TypeOptions; // tree配置项，包含label children disabled isLeaf class
    fetchApi: PropType<TypeFetchApi | Array<any>>; // 请求tree数据的接口
}

const props = withDefaults(defineProps<PropsType>(), {
    modelValue: 0,
    multiple: false,
    defaultProps: () => ({ children: 'children', label: 'name' }),
    fetchApi: () => []
});

const emits = defineEmits<{
    (e: 'update:modelValue', id: number | string): void;
}>();

/**
 * @description: tree节点点击事件
 * @param {*} id
 * @return {*}
 */
const nodeClickHandle = ({ id }: any) => {
    currentNodeKey.value = id;
};

/**
 * @description: 格式化tree
 * @param {*} arr
 * @return {*}
 */
const formatTreeData = (arr: any[]) => {
    const newArr: any[] = [...arr];
    if (newArr.length) {
        newArr.forEach(item => {
            item.name = `${item.name}（${item.nums || 0}）`;
            if (item?.children?.length) {
                item.children = formatTreeData(item.children);
            }
        });
    }
    return newArr;
};

/**
 * @description: 初始化tree，加上全部分组
 * @param {*} res
 * @return {*}
 */
const initData = res => {
    if (res?.data?.length) {
        const { data: children, total: nums } = res;
        if (children.length) {
            currentNodeKey.value = children[0].id;
            const id = 'all';
            const name = '全部分组';
            treeData.value = formatTreeData([{ id, name, nums, children }]);
        }
    }
};

/**
 * @description: 获取tree数据
 * @return {*}
 */
const getTreeData = async () => {
    if (!type.isFunction(props.fetchApi) && !type.isPromise(props.fetchApi) && !type.isArray(props.fetchApi)) return;
    let params: any = {};
    let fetchApi: any = props.fetchApi;
    if (type.isPromise(fetchApi)) fetchApi = await fetchApi;
    if (type.isArray(fetchApi)) {
        const [extra, fetch] = fetchApi;
        params = { ...extra, ...params };
        fetchApi = fetch;
    }
    const res = (await fetchApi?.(params)) ?? {};
    initData(res);
};

onMounted(async () => {
    await getTreeData();
});
</script>
